/*
 * @Author: hq
 * @Date: 2022-05-18 19:57:54
 * @LastEditors: hq
 * @LastEditTime: 2022-08-15 09:49:20
 * @Description: your project
 * @version: 1.0
 */
import sort_ascii from "../utils/signature"
import axios from "axios";
import router from "../router";
import {
    Message
} from "element-ui";
const service = axios.create({
    // baseURL: "https://api.zjht.zgdjkpt.com/adm/",
    baseURL: window.LOCATIONURL, //"https://test.zjht.zgdjkpt.com/adm/",
    timeout: 80000,
});
import md5Libs from "@/utils/md5";
let token = "0"
var appkey = "348c8d50475f21a344b195052a06ecfe38e334ba"
var secret = "541821fc6448ac4d8a3bc7eb43cabca7dd48885b"
var cdnkey = "D541j17rx2JXQkZ1p9xNj1ZbJSW8ghG9r0bd3lB8"
// var version = "0.0.01"
const get_apiurl = (i, b) => {
    let timestamp = parseInt(new Date().getTime() / 1000);
    let none_str = str_rand(40);
    let version = "3.1.1"
    let token = sessionStorage.getItem("token") || '0';
    let p1 = {
        appkey: appkey,
        model: 'webapp',
        os: 'windows',
        version: version,
        platform: 'web',
        none_str: none_str
    };
    let p2 = Object.keys(p1).map(function (key) {
        return (key) + "=" + (p1[key]);
    }).join("&");
    let s1 = 'action=' + i + '&appkey=' + appkey + '&model=' + p1.model + '&os=' + p1.os + '&version=' + version + '&timestamp=' + timestamp + '&platform=' + p1.platform + '&none_str=' + none_str + '&token=' + token;
    let s2 = md5Libs.md5(s1) + secret;
    let s3 = md5Libs.md5(s2);
    // console.log("i"i)
    let a1 = '/' + b + '/' + i + '.json-' + timestamp + '-' + s3 + '-' + token + '-' + cdnkey;
    let a2 = timestamp + '-' + s3 + '-' + token + '-' + md5Libs.md5(a1);
    return '/' + b + '/' + i + '.json?' + p2 + '&access_token=' + a2;
}
const str_rand = (l, c) => {
    let min = 0,
        _str = '';
    l = l || 32;
    c = c || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for (var i = 0, index; i < l; i++) {
        _str += c[parseInt(Math.random() * c.length)];
    }
    return _str;
}

service.interceptors.request.use(
    (config) => {
        let saveUrl = config.url
        config.url = get_apiurl(config.url, config.base ? config.base : 'webadminapi')
        config.data['timestamp'] = Date.parse(new Date()) / 1000; //当前时间
        config.data['sign'] = sort_ascii(config.data);
        config.data['platform'] = 'sys_web';
        //如果登录之后  长时间未操作
        if (saveUrl !== 'login/login' && saveUrl !== 'menu/index') {
            if (token !== '0') {
                //4小时长时间未操作 过期
                if (config.data['timestamp'] - Number(sessionStorage.getItem("last_req_time")) > 3000) { //50分钟
                    Message({
                        message: "您长时间未操作，请重新登陆！",
                        type: "warning",
                        showClose: true,
                    });
                    sessionStorage.clear()
                    router.replace({
                        path: "/login",
                    });
                } else {
                    //续签
                    let expire_time = Number(sessionStorage.getItem('expire_time')) - config.data['timestamp']
                    if (expire_time < 3200) { //小于*小时信息续签  调接口
                        axios({
                            url: window.LOCATIONURL + get_apiurl("login/renewToken", 'webadminapi'),
                            method: 'POST',
                            params: {
                                timestamp: Date.parse(new Date()) / 1000, //当前时间
                                sign: sort_ascii({})
                            },
                        }).then(res => {
                            sessionStorage.setItem("token", res.data.data.token);
                            sessionStorage.setItem("username", res.data.data.name);
                            sessionStorage.setItem("expire_time", res.data.data.expire_time);
                        })
                    }
                }

            }
        }


        //可添加请求头
        if (token == '0' && sessionStorage.getItem("token")) {
            token = sessionStorage.getItem("token");
        }
        return config;
    },
    (error) => {
        console.log("出错啦", error); // for debug
        Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response) => {
        if (token !== '0') {
            sessionStorage.setItem("last_req_time", Date.parse(new Date()) / 1000)
        }
        if (response.data.err === 0) {
            return response.data
        } else if (response.data.err === 200001 || response.data.err === 10110) {
            if (document.getElementsByClassName("el-message").length > 0)
                return false;
            Message({
                message: response.data.msg,
                type: "error",
                showClose: true,
            });
            router.replace({
                path: "/login",
            });
        } else {
            if (document.getElementsByClassName("el-message").length > 0)
                return false;
            Message({
                message: response.data.msg,
                type: "error",
                showClose: true,
            });
        }

    },

    (error) => {
        //加载超时提示
        if (document.getElementsByClassName("el-message").length > 0) return false;
        Message({
            message: "加载超时，请稍后重试",
            type: "error",
            showClose: true,
        });
        console.log("err" + error); // for debug
        return Promise.reject(error);
    }
);

export default service;